package com.example.inventoryservice.dao;

import com.example.inventoryservice.bean.Inventory;
import org.apache.ibatis.annotations.*;

@Mapper
public interface InventoryDao {
    @Select("select * from inventory where productId = #{productId}")
    Inventory findByProductId(Long productId);

    @Insert("insert into inventory(productId, totalStock, lockedStock, availableStock) " +
            "values(#{productId}, #{totalStock}, #{lockedStock}, #{availableStock})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(Inventory inventory);

    @Update("update inventory set totalStock = #{totalStock}, lockedStock = #{lockedStock}, availableStock = #{availableStock} where product_id = #{productId}")
    int update(Inventory inventory);

    // 锁定库存
    @Update("update inventory set lockedStock = lockedStock + #{quantity}, availableStock = availableStock - #{quantity} " +
            "where productId = #{productId} and availableStock >= #{quantity}")
    int lockStock(@Param("productId") Long productId, @Param("quantity") Integer quantity);

    // 释放库存
    @Update("update inventory set lockedStock = lockedStock - #{quantity}, availableStock = availableStock + #{quantity} " +
            "where productId = #{productId} and lockedStock >= #{quantity}")
    int releaseStock(@Param("productId") Long productId, @Param("quantity") Integer quantity);

    // 扣减库存
    @Update("update inventory set totalStock = totalStock - #{quantity}, lockedStock = lockedStock - #{quantity} " +
            "where productId = #{productId} and lockedStock >= #{quantity}")
    int deductStock(@Param("productId") Long productId, @Param("quantity") Integer quantity);
}